package com.framework.loippi.controller.admin;

import com.framework.loippi.controller.GenericController;
import com.framework.loippi.dto.admin.GainVo;
import com.framework.loippi.entity.Payment;
import com.framework.loippi.mybatis.paginator.domain.Order;
import com.framework.loippi.mybatis.paginator.domain.Order.Direction;
import com.framework.loippi.service.PaymentService;
import com.framework.loippi.service.UserService;
import com.framework.loippi.support.ExcelView;
import com.framework.loippi.support.Message;
import com.framework.loippi.support.Page;
import com.framework.loippi.support.Pageable;
import com.framework.loippi.utils.Dateutil;
import com.framework.loippi.utils.ParameterUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Controller - 交易流水
 *
 * @author Mounate Yan。
 * @version 1.0
 */
@Controller("adminPaymentController")
@RequestMapping({"/admin/payment"})
public class PaymentController extends GenericController {

    @Resource
    private PaymentService paymentService;

    @Resource
    private UserService userService;


    /**
     * 跳转添加页面
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = {"/add"}, method = {RequestMethod.GET})
    public String add(ModelMap model) {
        return "/admin/payment/add";
    }

    /**
     * 保存
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save(Payment payment, RedirectAttributes redirectAttributes) {
        payment.setCreateDate(new Date());
        paymentService.save(payment);
        addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
        return "redirect:list.jhtml";
    }

    /**
     * 编辑
     */
    @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
    public String edit(@PathVariable Long id, ModelMap model) {
        Payment payment = paymentService.find(id);
        model.addAttribute("payment", payment);
        return "/admin/payment/edit";
    }

    /**
     * 更新
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String update(Payment ad, RedirectAttributes redirectAttributes) {
        paymentService.update(ad);
        addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
        return "redirect:list.jhtml";
    }

    /**
     * 列表查询
     *
     * @param pageable
     * @param model
     * @return
     */
    @RequestMapping(value = {"/list"}, method = {RequestMethod.GET})
    public String list(Pageable pageable, HttpServletRequest request, ModelMap model) {
        Map<String, Object> paramter = ParameterUtils.getParametersMapStartingWith(request, "filter_");
        pageable.setParameter(paramter);
        pageable.setOrderProperty("PAY_DATE");
        pageable.setOrderDirection(Direction.DESC);
        Page<Payment> page = this.paymentService.findByPage(pageable);
        model.addAttribute("page", page);
        model.addAttribute("paramter", paramter);
        GainVo day = paymentService.day();
        GainVo week = paymentService.week();
        GainVo month = paymentService.month();
        model.addAttribute("day", day);
        model.addAttribute("week", week);
        model.addAttribute("month", month);
        return "/admin/payment/list";
    }

    /**
     * 健康档案导出Excel
     *
     * @param pageable
     * @param model
     * @return
     */
    @RequestMapping(value = {"/exportExcel"}, method = {RequestMethod.GET})
    @ResponseBody
    public void exportExcel(ModelMap model,
                            HttpServletRequest request, HttpServletResponse response, Long[] ids) {
        Map<String, Object> paramter = ParameterUtils.getParametersMapStartingWith(request, "filter_");
        Order order = new Order();
        order.setProperty("PAY_DATE");
        order.setDirection(Direction.DESC);
        paramter.put("order", order);
        List<Payment> findList = this.paymentService.findList(paramter);
        for (Payment payment : findList) {
            // 对日期格式进行转换
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            payment.setCreateDateStr(sdf.format(payment.getPayDate()));
            //业务类型(1-会员购买，2-金币充值,3-礼物打赏)
            if (payment.getBizType() == 1) {
                payment.setBizTypeStr("会员购买");
            } else if (payment.getBizType() == 2) {
                payment.setBizTypeStr("金币充值");
            }
            //收入状态(1-收入， 0 - 支出)
            if (payment.getGainStatus() == 1) {
                payment.setGainStatusStr("收入");
            } else {
                payment.setGainStatusStr("支出");
            }
        }
        String[] properties = {"sn", "account", "createDateStr", "amount", "bizTypeStr", "gainStatusStr"};
        String[] titles = {"交易流水号", "手机号", "交易时间", "交易金额(元)", "类型", "收入/支出"};
        ExcelView ev = new ExcelView("交易流水" + Dateutil.getCurrTime() + ".xls", "交易流水", properties,
                titles, new Integer[]{8000, 5000, 6000, 4000, 5000, 4000}, null,
                findList, null);
        HSSFWorkbook hwb = new HSSFWorkbook();
        try {
            ev.buildExcelDocument(model, hwb, request, response);
            hwb.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 删除操作
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = {"/delete"}, method = {RequestMethod.POST})
    @ResponseBody
    public Message delete(Long[] ids) {
        if (ids.length >= this.paymentService.count())
            return Message.error("admin.common.deleteAllNotAllowed",
                    new Object[0]);
        this.paymentService.deleteAll(ids);
        return SUCCESS_MESSAGE;
    }
}
